package com.atkxp.sys.handler;

import com.alibaba.fastjson2.JSON;
import com.atkxp.sys.entity.Result;
import com.atkxp.sys.utils.WebUtils;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author longhunpomie
 * @declaration
 * @email 3314028177@qq.com
 * @create 2023/9/15-19:36
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        Result<Object> fail = null;
        if(e instanceof AuthenticationCredentialsNotFoundException) {
            fail = Result.fail(20003, e.getMessage());
        } else {
            fail = Result.fail(20003, "登录已失效，请重新登录");
        }



        WebUtils.renderString(httpServletResponse, JSON.toJSONString(fail));
    }
}
